import React, {Component} from 'react';
import {
  Animated,
  View,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
  TouchableWithoutFeedback,
  Modal,
  Text,
  Keyboard,
  Image,
  ScrollView,
  FlatList,
  DeviceEventEmitter,
  PermissionsAndroid,
} from 'react-native';
import ModalHandler from '../../components/ModalHandler';
import BaseComponent from '../base/BaseComponent';
import {connect} from 'react-redux';
import {NormalHeader} from '../../components/NavigationHeader';
import I18n from 'react-native-i18n';
import Layout from '../../config/LayoutConstants';
import PropTypes from 'prop-types';
import {queryWalltBalance} from '../../redux/action/index';
import {
  TextButton,
  ImageButton,
  ImageTitleButton,
  LinearBoardButton,
  LinearButton,
} from '../../components/Button';
import {TextInput} from 'react-native-gesture-handler';
import {
  queryChannelNormalUsers,
  queryChannelSpeakers,
  changeMemberStatus,
  closeMicphone,
  queryChannelAuctions,
  queryChannel,
} from '../../api/channel/index';
import {
  setCurrentRoomSpeaker,
  setCurrentRoomListener,
  setRoomWidgetLayout,
  setCurrentRoom,
  updateUserInfo,
  setRoomKey,
} from '../../redux/action';
import {query, follow} from '../../api/user/index';
import WalletUtils from '../../utils/wallet/WalletUtils';
import {showToast} from '../../components/Toast';
import {BASE_API} from '../../config';
import moment from 'moment';
import AuctionCell from './components/AuctionCell';
import LinearGradient from 'react-native-linear-gradient';
import {
  activateKeepAwake,
  deactivateKeepAwake,
} from '@sayem314/react-native-keep-awake';
import BigNumber from 'bignumber.js';
import {formatMinuteTime, formatLeftTime} from '../../utils/tools';
import ChainUtils from '../../utils/chain/ChainUtils';
import {Colors} from '../../styles/common';
import {CachedImage} from 'react-native-img-cache';
import Device, {isIos} from '../../utils/device';
import StorageManager, {DID_SHOW_ROOM_LEAD} from '../../storage';

class RoomScreen extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      userModalVisible: false,
      giftModalVisible: false,
      showUser: {},
      micphoneState:
        props.navigation.state.params && props.navigation.state.params.creater
          ? true
          : false,
      auctions: [],
      modalVisible: false,
    };
  }

  _backgroundStateEmitter = (nextAppState) => {
    console.log('切换前后台');

    if (nextAppState != null && nextAppState === 'active') {
      //如果是true ，表示从后台进入了前台 ，请求数据，刷新页面。或者做其他的逻辑
      // this.getList();
    } else if (nextAppState != null && nextAppState === 'background') {
    }
  };

  componentDidMount() {
    super.componentDidMount();

    this.getList();

    this.queryListInterval = setInterval(() => {
      this.getList();

      queryChannel({
        userToken: this.props.userInfo.token,
        channelId: this.props.currentRoom.channelId,
      }).then(async (res) => {
        this.props.setCurrentRoom(res.data);
      });
    }, 5 * 1000);

    activateKeepAwake();

    this.props.setRoomKey(this.props.navigation.state.key);

    setTimeout(() => {
      DeviceEventEmitter.emit('enterRoomEmitter', true);
    }, 500);

    this.reconnectRoomEmiteer = DeviceEventEmitter.addListener(
      'reconnectSuccess',
      this.getList,
    );

    this.newOwnerEmitter = DeviceEventEmitter.addListener(
      'newOwner',
      this.optionNewOwner,
    );

    console.log('************');
    console.log(this.props.userInfo.isRoomOwner);
    console.log(this.props.userInfo.isSpeaker);

    if (!this.props.userInfo.isRoomOwner && !this.props.userInfo.isSpeaker) {
      StorageManager.load(DID_SHOW_ROOM_LEAD).then((res) => {
        if (res == undefined) {
          this.setState({
            modalVisible: true,
          });
        }
      });
    }
  }

  componentWillUnmount() {
    deactivateKeepAwake();

    if (this.reconnectRoomEmiteer) {
      this.reconnectRoomEmiteer.remove();
    }

    if (this.newOwnerEmitter) {
      this.newOwnerEmitter.remove();
    }

    clearInterval(this.queryListInterval);
  }

  optionNewOwner = (newUser) => {
    console.log('新的用户' + newUser);
    console.log(this.props.currentRoom.owner);
    this.props.setCurrentRoom({
      ...this.props.currentRoom,
      owner: newUser.userId,
    });
    console.log(this.props.currentRoom.owner);

    //清除举手列表

    let msg = `${newUser.nickName} has become the owner`;
    if (newUser.userId == this.props.userInfo.userId) {
      msg = `you has become the owner`;

      this.props.updateUserInfo({
        ...this.props.userInfo,
        isRoomOwner: true,
      });
    }

    //如果用户再观众席，则移动到主持席
    if (!this.props.userInfo.isSpeaker) {
      //上麦
      DeviceEventEmitter.emit('channelMessage', {
        type: 'agreeRaisedHand',
        data: {
          identify: this.props.userInfo.identify,
          microphone: 0,
        },
      });
    }

    this._showAlert({
      content: msg,
    });
  };

  getList = () => {
    console.log('查询房间内用户列表$$$$$$$$$$');

    if (!this.props.currentRoom || !this.props.currentRoom.channelId) {
      return;
    }

    let data = {
      userToken: this.props.userInfo.token,
      channelId: this.props.currentRoom.channelId,
    };

    queryChannelSpeakers(data)
      .then((res) => {
        console.log('查询的上麦用户信息为：' + JSON.stringify(res));

        let speakers = res.data.map((item) => {
          return {
            ...item,
            id: item.identify,
            followerNum: item.followAmount,
            followingNum: item.fansAmount,
            bio: item.introduction,
            name: item.nickName,
            avatar: BASE_API + item.image,
            userId: item.userId,
            isRoomOwner: item.userId == this.props.currentRoom.owner,
          };
        });
        this.props.setCurrentRoomSpeaker(speakers);
      })
      .catch((err) => {
        console.log('查询上麦用户失败' + err);
      });

    queryChannelNormalUsers(data)
      .then((res) => {
        console.log('查询房间内的听众列表为');
        console.log(res);

        let listeners = res.data.map((item) => {
          return {
            ...item,
            id: item.identify,
            followerNum: item.followAmount,
            followingNum: item.fansAmount,
            bio: item.introduction,
            name: item.nickName,
            userId: item.userId,
            avatar: BASE_API + item.image,
            isRoomOwner: item.userId == this.props.currentRoom.owner,
          };
        });

        this.props.setCurrentRoomListener(listeners);
      })
      .catch((err) => {
        console.log('查询普通用户失败' + err);
      });

    queryChannelAuctions(data).then((res) => {
      console.log('查询到channel内的频道为');
      console.log(JSON.stringify(res, null, 2));

      try {
        let newActions = res.data.map((item) => {
          // console.log(item.expireDate);

          let timeSpace =
            new Date(item.expireDate * 1000) - new Date().valueOf();

          let startPrice = new BigNumber(item.startPrice);
          const decimal = new BigNumber(Math.pow(10, item.payCoinDecimal));
          let vAmount = parseFloat(startPrice.dividedBy(decimal));

          startPrice = ChainUtils.subStringNum(vAmount, 4);

          let bidValue = new BigNumber(item.bidValue);
          let bAmount = parseFloat(bidValue.dividedBy(decimal));
          bidValue = ChainUtils.subStringNum(bAmount, 4);

          let dealPrice = new BigNumber(item.dealPrice);
          let dAmount = parseFloat(dealPrice.dividedBy(decimal));
          dealPrice = ChainUtils.subStringNum(dAmount, 4);

          return {
            ...item,
            img: item.img,
            leftTime: formatLeftTime(timeSpace),
            startPrice,
            bidValue,
            dealPrice,
          };
        });

        this.setState({
          auctions: newActions,
        });
      } catch (err) {
        console.log('获取channel内拍卖信息错误' + err);
      }
    });
  };

  _quit = () => {
    Keyboard.dismiss();

    console.log('离开房间，关闭ws连接');
    this.levaeRoom = true;
  };

  onUserPress = (user) => {
    if (user.id == this.props.userInfo.identify) {
      return;
    }
    //查询用户信息
    query({userToken: this.props.userInfo.token, identify: user.id})
      .then((res) => {
        // console.log(res);
        this.props.setRoomWidgetLayout({bottom: -1000});
        this.setState({
          userModalVisible: true,
          showUser: {
            id: res.data.identify,
            followerNum: res.data.fansAmount,
            followingNum: res.data.followAmount,
            relationship: res.data.relationship,
            bio: res.data.introduction,
            name: res.data.nickName,
            address: res.data.address,
            avatar: BASE_API + res.data.image,
            isSpeaker: res.data.isSpeaker,
            userId: res.data.userId,
          },
        });
      })
      .catch((err) => {
        console.log('查询用户信息错误' + err);
      });
  };

  followPress = () => {
    console.log('点击follow操作', JSON.stringify(this.state.showUser, null, 2));
    follow({
      userToken: this.props.userInfo.token,
      identify: this.state.showUser.id,
      event: this.state.showUser.relationship != 0 ? '0' : '1',
    }).then((res) => {
      console.log('follow操作结果' + res);
      this.setState({
        showUser: {
          id: res.data.identify,
          followerNum: res.data.fansAmount,
          followingNum: res.data.followAmount,
          relationship:
            this.state.showUser.relationship == 1 ||
            this.state.showUser.relationship == 2
              ? 0
              : 1,
          bio: res.data.introduction,
          name: res.data.nickName,
          address: res.data.address,
          avatar: BASE_API + res.data.image,
          isSpeaker: res.data.isSpeaker,
          userId: res.data.userId,
        },
      });
    });
  };

  onSpeakPress = (item) => {
    console.log('onSpeakPress' + item);

    changeMemberStatus({
      userToken: this.props.userInfo.token,
      type: 1,
    })
      .then((res) => {
        console.log('上麦成功');

        this.props.updateUserInfo({
          ...this.props.userInfo,
          isSpeaker: 1,
          micphoneState: 1,
        });

        DeviceEventEmitter.emit('micphoneChange', true);
      })
      .catch((res) => {
        console.log('上麦失败');
      });
  };

  needSendGift = async (coins, password, value) => {
    if (coins.length == 0) {
      this._showAlert({content: I18n.t('room.selToken')});
      return;
    }

    if (password.length == 0) {
      this._showAlert({content: I18n.t('room.inputPassword')});
      return;
    }

    if (value.length == 0) {
      this._showAlert({content: I18n.t('room.tokenAmount')});
      return;
    }

    console.log(coins, password, value);
    // console.log(this.state.showUser);

    let coin = coins[0];

    if (Number(coin.balance) < Number(value)) {
      this._showAlert({content: 'invalid balance'});
      return;
    }

    this._showLoading(I18n.t('room.decrypting'));

    try {
      let privateKey = await WalletUtils.privateKeyOfKeystore(
        this.props.userInfo.keystore,
        password,
      );

      this._showLoading(I18n.t('room.pending'));

      if (!coin.isErc20) {
        WalletUtils.transferHeco(
          privateKey,
          this.state.showUser.address,
          value,
          (hash) => {
            this.setState({
              result: '交易已发送，正在监听交易->' + hash,
            });
          },
        )
          .then((res) => {
            console.log('交易已确认' + JSON.stringify(res, null, 2));
            this._hideLoading();
            this.setState({
              giftModalVisible: false,
            });
          })
          .catch((err) => {
            this._hideLoading();
            this._showAlert({content: err + ''});
          });
      } else {
        WalletUtils.transferErc20(
          privateKey,
          this.state.showUser.address,
          value,
          coin.contractAddress,
          coin.decimal,
          (hash) => {
            console.log('已发送交易，正在pending', hash);
            // this.setState({
            //   result: '交易已发送，正在监听交易->' + hash,
            // });
          },
        )
          .then((res) => {
            console.log('交易已确认' + JSON.stringify(res, null, 2));
            this._hideLoading();
            this.setState({
              giftModalVisible: false,
            });

            showToast(I18n.t('room.giveGift'));
          })
          .catch((err) => {
            this._hideLoading();
            this._showAlert({content: err + ''});
          });
      }
    } catch (err) {
      console.log('发送错误' + err);
      this._hideLoading();
      let msg = err.toString();
      if (err.toString().indexOf('authentication code mismatch')) {
        msg = 'password error';
      }
      this._showAlert({content: msg});
    }
  };

  closeUserMicphone = (user) => {
    closeMicphone({
      userToken: this.props.userInfo.token,
      identify: user.id,
    })
      .then((res) => {
        console.log('操作成功，将用户下麦');
      })
      .catch((err) => {
        console.log(err);
        console.log('用户强制下麦失败');
      });
  };

  _onPressAuction = async (item) => {
    console.log('点击拍卖详情');
    this.props.navigation.navigate('Auction', {auction: item});
  };

  _renderAuctionCellItem = (item) => (
    <AuctionCell
      auction={item.item}
      swapSymbol={this.props.swapSymbol}
      onPressItem={() => this._onPressAuction(item.item)}
    />
  );

  _renderItemSeparatorComponent = () => (
    <View style={{height: 1, backgroundColor: 'rgba(220,220,220,0.5)'}} />
  );

  renderComponent = () => {
    let {offlineUser, currentRoom} = this.props;
    let {auctions, modalVisible} = this.state;

    let alertImageWidth = Device.getDeviceWidth() - 80;
    let alertImageHeight = (alertImageWidth * 107) / 366;

    return (
      <View style={{backgroundColor: '#160231', flex: 1, padding: 0}}>
        <NormalHeader
          navigation={this.props.navigation}
          right={{
            icon: require('../../assets/common/quit.png'),
            onPress: () => {
              Keyboard.dismiss();
              // this.setState({
              //   modalVisible: true,
              // });

              if (this.props.currentRoom.owner == this.props.userInfo.userId) {
                this._showAlert({
                  content: 'Select your action to exit the room',
                  cancelTitle: 'Exit',
                  alertCancelPress: () => {
                    console.log('退出房间');
                    DeviceEventEmitter.emit('userQuitRoom');
                  },
                  okTitle: 'Dissoution',
                  alertOkPress: () => {
                    console.log('解散房间');
                    DeviceEventEmitter.emit('userQuitRoom', {
                      dissolution: true,
                    });
                  },
                  bgDismissEnable: true,
                });
              } else {
                this._showAlert({
                  content: 'are you sure to exit room?',
                  cancelTitle: 'cancel',
                  alertOkPress: () => {
                    DeviceEventEmitter.emit('userQuitRoom');
                  },
                });
              }
            },
            // icon: require('../../assets/common/room_back.png'),
            // text:
            // this.props.navigation.state.params &&
            // this.props.navigation.state.params.from == 'other'
            //   ? 'Back'
            //   : I18n.t('room.all_room'),
            // onPress: () => {
            //   this.props.setRoomKey('');

            //   let {navigation} = this.props;
            //   if (navigation.state.params && navigation.state.params.backKey) {
            //     navigation.goBack(navigation.state.params.backKey);
            //   } else {
            //     navigation.goBack();
            //   }
            // },
          }}
          left={{
            containerStyle: {
              paddingLeft: 4,
              paddingRight: 4,
              paddingTop: 4,
              paddingRight: 4,
            },
            mode: 'cover',
            onPress: () => {
              Keyboard.dismiss();
              this.quitRoomPage();
            },
            imageStyle: {borderRadius: 10, width: 20, height: 20},
            text:
              this.props.navigation.state.params &&
              this.props.navigation.state.params.from == 'home'
                ? I18n.t('room.all_room')
                : 'Minimize',
            icon: require('../../assets/common/arrow_down.png'),
          }}
        />
        <ScrollView style={{flex: 1, width: Layout.WINDOW_WIDTH}}>
          <View
            style={{
              margin: 20,
              borderRadius: 10,
              paddingTop: 10,
              position: 'relative',
            }}>
            <LinearGradient
              start={{x: 0, y: 1}}
              end={{x: 1, y: 1}}
              colors={['#CE18EC', '#6601F5']}
              style={{padding: 2, borderRadius: 10}}>
              <View
                style={{flex: 1, borderRadius: 8, backgroundColor: 'white'}}>
                <View
                  style={{
                    flex: 1,
                    marginLeft: 80,
                    height: 40,
                    paddingRight: 20,
                  }}>
                  <Text
                    style={{
                      color: '#6D03F4',
                      fontWeight: 'bold',
                      fontSize: 18,
                      height: 40,
                      lineHeight: 40,
                    }}>
                    {currentRoom ? currentRoom.name : ''}
                  </Text>
                  <Image
                    style={{height: 1, width: '100%'}}
                    source={require('../../assets/auction/line.png')}></Image>
                </View>
                <View
                  style={{
                    paddingBottom: 20,
                    flexDirection: 'row',
                    flexWrap: 'wrap',
                    alignItems: 'flex-start',
                  }}>
                  {this.props.speakers
                    .filter((item, idx) => idx < 9)
                    .map((speaker, index) => {
                      return (
                        <View
                          key={'spe' + speaker.identify}
                          style={{
                            flexDirection: 'column',
                            paddingLeft: 4,
                            paddingRight: 4,
                            width: '33.3%',
                            justifyContent: 'center',
                            alignItems: 'center',
                            marginTop: 10,
                          }}>
                          <TouchableOpacity
                            onPress={() => this.onUserPress(speaker)}>
                            <CachedImage
                              style={{width: 80, height: 80, borderRadius: 100}}
                              source={{uri: speaker.avatar}}
                            />
                            {offlineUser.some(
                              (item) => item.id == speaker.id,
                            ) ? (
                              <View
                                style={{
                                  position: 'absolute',
                                  width: 80,
                                  height: 80,
                                  left: 0,
                                  top: 0,
                                  borderRadius: 40,
                                  backgroundColor: 'rgba(200,200,200,0.8)',
                                }}></View>
                            ) : null}
                            {speaker.mute ? (
                              <Image
                                style={{
                                  width: 20,
                                  height: 20,
                                  position: 'absolute',
                                  right: 0,
                                  bottom: 2,
                                }}
                                source={require('../../assets/room/microphone_mute.png')}
                              />
                            ) : null}
                            {this.props.currentRoom &&
                            speaker.userId == this.props.currentRoom.owner ? (
                              <Image
                                style={{
                                  width: 25,
                                  height: 25,
                                  position: 'absolute',
                                  right: 0,
                                  bottom: 0,
                                }}
                                source={require('../../assets/room/owner.png')}
                              />
                            ) : null}
                          </TouchableOpacity>
                          <View
                            style={{
                              flexDirection: 'row',
                              alignItems: 'center',
                              justifyContent: 'center',
                              marginLeft: -23,
                            }}>
                            <View
                              style={{
                                marginRight: 5,
                                position: 'relative',
                              }}>
                              <Image
                                source={require('../../assets/room/user-speaker-micphone.png')}
                                style={{width: 18, height: 18}}
                              />
                              <View
                                style={{
                                  position: 'absolute',
                                  backgroundColor: 'transparent',
                                  width: 4,
                                  height: 10,
                                  left: 7,
                                  bottom: 7,
                                  borderRadius: 2,
                                  overflow: 'hidden',
                                  // borderBottomLeftRadius: 2,
                                  // borderBottomRightRadius: 2,
                                }}>
                                <View
                                  style={{
                                    position: 'absolute',
                                    backgroundColor: '#6D03F4',
                                    width: '100%',
                                    height: this.props.speakingUsers.some(
                                      (item) => item.uid == speaker.userId,
                                    )
                                      ? Math.round(
                                          (this.props.speakingUsers.filter(
                                            (item) =>
                                              item.uid == speaker.userId,
                                          )[0].volume /
                                            100) *
                                            10,
                                        )
                                      : 0,
                                    left: 0,
                                    bottom: 0,
                                  }}></View>
                              </View>
                            </View>
                            <Text
                              style={{
                                color: '#6D03F4',
                                fontWeight: 'bold',
                                fontSize: 12,
                              }}
                              numberOfLines={1}>
                              {speaker.name}
                            </Text>
                          </View>
                        </View>
                      );
                    })}
                  {/* {this.props.speakers && this.props.speakers.length < 9
                    ? new Array(9 - this.props.speakers.length)
                        .fill('')
                        .map((speaker, index) => {
                          return (
                            <View
                              key={'speakers' + index}
                              style={{
                                paddingLeft: 4,
                                paddingRight: 4,
                                width: '33.3%',
                                justifyContent: 'center',
                                alignItems: 'center',
                                marginTop: 20,
                              }}>
                              <TouchableOpacity
                                style={{
                                  width: 80,
                                  height: 80,
                                  backgroundColor: '#D8D8D8',
                                  borderRadius: 100,
                                  justifyContent: 'center',
                                  alignItems: 'center',
                                }}
                                onPress={this.onSpeakPress}>
                                <Image
                                  style={{
                                    width: 16,
                                    height: 16,
                                  }}
                                  resizeMode="contain"
                                  source={require('../../assets/room/add.png')}
                                />
                              </TouchableOpacity>
                            </View>
                          );
                        })
                    : null} */}
                </View>
              </View>
            </LinearGradient>
            <Image
              style={{position: 'absolute', left: 20}}
              source={require('../../assets/room/talk_room.png')}></Image>
          </View>
          {auctions.length > 0 ? (
            <View
              style={{
                maxHeight: 300,
                borderRadius: 10,
                marginTop: 10,
                marginBottom: 20,
              }}>
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  marginLeft: 20,
                  marginRight: 20,
                }}>
                <Text
                  style={{
                    color: 'white',
                    fontWeight: 'bold',
                    fontSize: 18,
                    marginRight: 20,
                  }}>
                  Auctions
                </Text>
                <Image
                  style={{height: 1, flex: 1}}
                  source={require('../../assets/auction/line.png')}></Image>
              </View>
              <FlatList
                style={{width: '100%', marginBottom: 20}}
                data={this.state.auctions}
                keyExtractor={(item, index) => item.auctionId} // 给定的item生成一个不重复的key
                renderItem={this._renderAuctionCellItem}
                ItemSeparatorComponent={this._renderItemSeparatorComponent}
              />
            </View>
          ) : null}
          {/* listener */}
          {this.props.currentRoom && !this.props.currentRoom.isCommonRoom ? (
            <View
              style={{
                margin: 20,
                borderRadius: 10,
                paddingTop: 10,
                paddingBottom: 20,
                position: 'relative',
              }}>
              <LinearGradient
                start={{x: 0, y: 1}}
                end={{x: 1, y: 1}}
                colors={['#CE18EC', '#6601F5']}
                style={{padding: 2, borderRadius: 10}}>
                <View
                  style={{flex: 1, borderRadius: 10, backgroundColor: 'white'}}>
                  <View
                    style={{
                      flex: 1,
                      marginLeft: 80,
                      height: 40,
                      paddingRight: 20,
                    }}>
                    <Text
                      style={{
                        color: '#6D03F4',
                        fontWeight: 'bold',
                        fontSize: 18,
                        height: 40,
                        lineHeight: 40,
                      }}>
                      Audience
                    </Text>
                    <Image
                      style={{height: 1, width: '100%'}}
                      source={require('../../assets/auction/line.png')}></Image>
                  </View>
                  <View
                    style={{
                      paddingBottom: 20,
                      flexDirection: 'row',
                      flexWrap: 'wrap',
                      alignItems: 'flex-start',
                    }}>
                    {this.props.listeners &&
                    this.props.listeners.length != 0 ? (
                      this.props.listeners.map((listener, index) => {
                        return (
                          <View
                            key={'listenrs' + index}
                            style={{
                              flexDirection: 'column',
                              paddingLeft: 4,
                              paddingRight: 4,
                              width: '33.3%',
                              justifyContent: 'center',
                              alignItems: 'center',
                              marginTop: 20,
                            }}>
                            <TouchableOpacity
                              onPress={() => this.onUserPress(listener)}>
                              <CachedImage
                                style={{
                                  width: 80,
                                  height: 80,
                                  borderRadius: 100,
                                }}
                                source={{uri: listener.avatar}}
                              />
                              {offlineUser.some(
                                (item) => item.id == listener.id,
                              ) ? (
                                <View
                                  style={{
                                    position: 'absolute',
                                    width: 80,
                                    height: 80,
                                    left: 0,
                                    top: 0,
                                    borderRadius: 40,
                                    backgroundColor: 'rgba(200,200,200,0.8)',
                                  }}></View>
                              ) : null}
                              {this.props.currentRoom &&
                              listener.userId ==
                                this.props.currentRoom.owner ? (
                                <Image
                                  style={{
                                    width: 25,
                                    height: 25,
                                    position: 'absolute',
                                    right: 0,
                                    bottom: 0,
                                  }}
                                  source={require('../../assets/room/owner.png')}
                                />
                              ) : null}
                            </TouchableOpacity>
                            <Text
                              style={{
                                color: '#6D03F4',
                                fontSize: 12,
                                marginTop: 10,
                                fontWeight: 'bold',
                              }}
                              numberOfLines={1}>
                              {listener.name}
                            </Text>
                          </View>
                        );
                      })
                    ) : (
                      <View
                        style={{
                          marginTop: 10,
                          height: 30,
                          alignItems: 'center',
                          justifyContent: 'center',
                          flex: 1,
                        }}>
                        <Text>no Audiences.</Text>
                      </View>
                    )}
                  </View>
                </View>
              </LinearGradient>
              <Image
                style={{position: 'absolute', left: 20}}
                source={require('../../assets/room/listener_room.png')}></Image>
            </View>
          ) : null}
          <View
            style={{
              width: '100%',
              height: this.props.widgetLayout.show
                ? this.props.widgetLayout.height
                : 0,
              marginTop: 10,
            }}></View>
        </ScrollView>
        {this.state.userModalVisible ? (
          <UserInfoDialog
            navigation={this.props.navigation}
            isManager={
              this.props.currentRoom.owner == this.props.userInfo.userId
            }
            muteUsers={this.props.muteUsers}
            showGift={!this.props.userInfo.disableGift}
            user={this.state.showUser}
            visible={this.state.userModalVisible}
            followPress={this.followPress}
            onClose={() => {
              console.log('关闭送礼物视图');
              this.props.setRoomWidgetLayout({
                bottom: 0,
              });
              this.setState({
                userModalVisible: false,
                showUser: {},
              });
            }}
            onSendGift={() => {
              this.props.queryWalltBalance();
              this.setState({
                userModalVisible: false,
                giftModalVisible: true,
              });
            }}
            muteRemoteUser={() => {
              console.log('点击静音');
              console.log(this.state.showUser);
              DeviceEventEmitter.emit('muteUser', this.state.showUser.userId);
            }}
            closeUserMicphone={() => {
              this.props.setRoomWidgetLayout({
                bottom: 0,
              });
              DeviceEventEmitter.emit('channelMessage', {
                type: 'closeUserMicphone',
                data: {
                  identify: this.state.showUser.id,
                },
              });
              this.setState({
                userModalVisible: false,
                showUser: {},
              });
            }}
            transferOwner={() => {
              this.props.setRoomWidgetLayout({
                bottom: 0,
              });
              this.setState({
                userModalVisible: false,
              });
              this._showAlert({
                content: `Are you sure to transfer owner of this room to ${this.state.showUser.nickName}`,
                cancelTitle: 'Cancel',
                alertCancelPress: () => {
                  this.setState({
                    showUser: {},
                  });
                },
                okTitle: 'Sure',
                alertOkPress: () => {
                  DeviceEventEmitter.emit('channelMessage', {
                    type: 'transferOwner',
                    data: {
                      identify: this.state.showUser.id,
                    },
                  });
                  this.setState({
                    showUser: {},
                  });
                },
              });
            }}
            offUser={() => {
              this.props.setRoomWidgetLayout({
                bottom: 0,
              });
              DeviceEventEmitter.emit('channelMessage', {
                type: 'offUser',
                data: {
                  identify: this.state.showUser.id,
                },
              });
              this.setState({
                userModalVisible: false,
                showUser: {},
              });
            }}></UserInfoDialog>
        ) : null}
        {this.state.giftModalVisible ? (
          <GiftDialog
            user={this.state.showUser}
            visible={this.state.giftModalVisible}
            gifts={this.props.coins}
            sendGift={this.needSendGift}
            onClose={() => {
              this.props.setRoomWidgetLayout({
                bottom: 0,
              });
              this.setState({
                giftModalVisible: false,
                showUser: {},
              });
            }}></GiftDialog>
        ) : null}
        <Modal transparent visible={modalVisible}>
          <TouchableWithoutFeedback
            onPress={() => {
              this.setState({
                modalVisible: false,
              });
              StorageManager.save(DID_SHOW_ROOM_LEAD, '1');
            }}>
            <View
              style={{
                flex: 1,
                backgroundColor: 'rgba(255,255,255,0.6)',
                justifyContent: 'flex-end',
                alignItems: 'center',
              }}>
              <View
                style={{
                  // marginBottom: 100,
                  width: alertImageWidth,
                  height: alertImageHeight,
                  position: 'relative',
                }}>
                <Image
                  style={{
                    width: '100%',
                    height: '100%',
                    position: 'absolute',
                    top: 0,
                    left: 0,
                  }}
                  source={require('../../assets/room/alert_bg.png')}></Image>
                <View
                  style={{
                    height: '75%',
                    width: '100%',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}>
                  <Text style={{color: 'black'}}>
                    Raise your hand before you speak
                  </Text>
                </View>
              </View>
              <View
                style={{
                  height: 96,
                  width: '100%',
                  flexDirection: 'row',
                  justifyContent: 'flex-end',
                  paddingTop: 10,
                  paddingRight: 20,
                  position: 'relative',
                }}>
                <ImageTitleButton
                  btnStyle={{
                    width: 40,
                    height: 40,
                    borderRadius: 20,
                    backgroundColor: '#C917ED',
                  }}
                  imageStyle={{width: 15, height: 15}}
                  title={'Raise Hand'}
                  titleStyle={{fontSize: 12}}
                  source={require('../../assets/room/raise_hand.png')}
                  onPress={() => {}}
                />
                <Image
                  style={{
                    width: 55 * 1.036,
                    height: 55,
                    position: 'absolute',
                    top: 0,
                    right: 30,
                  }}
                  source={require('../../assets/room/circle.png')}></Image>
              </View>
            </View>
          </TouchableWithoutFeedback>
        </Modal>
      </View>
    );
  };
}

class UserInfoDialog extends Component {
  static propTypes = {
    navigation: PropTypes.object.isRequired,
    isManager: PropTypes.bool.isRequired,
    visible: PropTypes.bool.isRequired,
    user: PropTypes.object.isRequired,
    onSendGift: PropTypes.func.isRequired,
    onClose: PropTypes.func.isRequired,
    followPress: PropTypes.func.isRequired,
    closeUserMicphone: PropTypes.func.isRequired,
    offUser: PropTypes.func.isRequired,
    transferOwner: PropTypes.func.isRequired,
    showGift: PropTypes.bool.isRequired,
    muteRemoteUser: PropTypes.array.isRequired,
  };

  constructor(props) {
    super(props);
  }

  formatNum = (num) => {
    if (!num) return '0';
    return num >= 1e3 && num < 1e4
      ? (num / 1e3).toFixed(1) + 'k'
      : num >= 1e4
      ? (num / 1e4).toFixed(1) + 'w'
      : num;
  };

  render() {
    const {user, visible, onClose, onSendGift, followPress} = this.props;

    let isMuteUser = this.props.muteUsers.some((item) => item == user.userId);
    console.log('********');
    console.log(user);
    return (
      <View
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: visible ? '100%' : 0,
          height: '100%',
          backgroundColor: 'rgba(0,0,0,0.3)',
        }}>
        {/* <Modal
          onStartShouldSetResponder={() => false}
          animationType="slide"
          transparent
          visible={visible}
          onRequestClose={() => {}}
          onShow={() => {}}
        > */}
        <TouchableOpacity
          onPress={onClose}
          style={{flex: 1}}></TouchableOpacity>
        <View
          style={{
            borderTopLeftRadius: 20,
            borderTopRightRadius: 20,
            backgroundColor: 'rgba(255,255,255,0.95)',
            padding: 20,
            marginBottom: 0,
          }}>
          {/* <TouchableOpacity
            style={{
              position: 'absolute',
              backgroundColor: 'red',
              right: 20,
              top: 10,
              width: 30,
              height: 30,
              alignItems: 'center',
              justifyContent: 'center',
            }}
            onPress={() => {
              console.log('关闭');
              onClose();
            }}></TouchableOpacity> */}
          <ImageButton
            btnStyle={{
              position: 'absolute',
              width: 50,
              height: 50,
              right: 20,
              top: 0,
            }}
            imageStyle={{
              width: 15,
              height: 15,
              marginTop: -10,
            }}
            source={require('../../assets/room/close.png')}
            onPress={() => {
              console.log('关闭');
              onClose();
            }}
          />
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              padding: 10,
            }}>
            <TouchableOpacity
              onPress={() => {
                this.props.navigation.navigate('UserInfo');
                onClose();
              }}>
              <Image
                style={{width: 80, height: 80, borderRadius: 40}}
                source={{uri: user.avatar}}
              />
            </TouchableOpacity>
            {user.relationship != 0 ? (
              <LinearBoardButton
                buttonStyle={{
                  width: 150,
                  height: 30,
                }}
                text={
                  user.relationship == 2
                    ? I18n.t('room.mutualRelations')
                    : I18n.t('room.followed')
                }
                onPress={followPress}></LinearBoardButton>
            ) : (
              <LinearButton
                buttonStyle={{
                  width: 150,
                  height: 30,
                }}
                text={I18n.t('room.follow')}
                onPress={followPress}></LinearButton>
            )}
          </View>
          <Text
            style={{
              color: '#7304F3',
              fontSize: 18,
              fontWeight: 'bold',
              marginTop: 20,
              marginLeft: 10,
            }}>
            {user.name}
          </Text>
          <View style={{flexDirection: 'row', marginTop: 2, marginLeft: 10}}>
            <Text style={{color: '#7304F3', fontSize: 14}}>@{user.id}</Text>
          </View>
          <View style={{flexDirection: 'row', marginTop: 20, marginLeft: 10}}>
            <View style={{flexDirection: 'row', alignItems: 'center'}}>
              <Text
                style={{color: '#7304F3', fontSize: 18, fontWeight: 'bold'}}>
                {this.formatNum(user.followerNum)}
              </Text>
              <Text style={{color: '#393939', fontSize: 14, paddingLeft: 5}}>
                {I18n.t('room.followers')}
              </Text>
            </View>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                marginLeft: 30,
              }}>
              <Text
                style={{color: '#7304F3', fontSize: 18, fontWeight: 'bold'}}>
                {this.formatNum(user.followingNum)}
              </Text>
              <Text style={{color: '#393939', fontSize: 14, paddingLeft: 5}}>
                {I18n.t('room.following')}
              </Text>
            </View>
          </View>
          <Text
            style={{
              color: '#393939',
              fontSize: 14,
              marginTop: 22,
              marginLeft: 10,
            }}
            numberOfLines={5}>
            {user.bio}
          </Text>
          <View style={{flexDirection: 'row', marginTop: 50}}>
            {/* {this.props.showGift ? (
              <ImageTitleButton
                btnStyle={{
                  width: 50,
                  height: 50,
                  backgroundColor: '#C817EC',
                  borderRadius: 25,
                }}
                imageStyle={{width: 25, height: 25}}
                title={'Send gift'}
                titleStyle={{color: Colors.fontBlackColor_31}}
                source={require('../../assets/room/gift.png')}
                onPress={onSendGift}
              />
            ) : null} */}
            {/* 管理员权限 */}
            <View
              style={{
                flex: 1,
                flexDirection: 'row',
                justifyContent: 'flex-start',
              }}>
              {/* 禁止用户说话 */}
              {this.props.isManager && user.isSpeaker ? (
                <ImageTitleButton
                  btnStyle={{
                    width: 50,
                    height: 50,
                    backgroundColor: '#C817EC',
                    borderRadius: 25,
                  }}
                  imageStyle={{width: 15, height: 25}}
                  title={'Mute'}
                  titleStyle={{color: Colors.fontBlackColor_31}}
                  source={require('../../assets/common/microphone.png')}
                  onPress={this.props.closeUserMicphone}
                />
              ) : null}
              {user.isSpeaker ? (
                <ImageTitleButton
                  btnStyle={{
                    width: 50,
                    height: 50,
                    backgroundColor: '#C817EC',
                    borderRadius: 25,
                  }}
                  imageStyle={{width: 25, height: 20}}
                  title={isMuteUser ? 'Cancel Mute' : 'Mute'}
                  titleStyle={{color: Colors.fontBlackColor_31}}
                  containerStyle={{width: 100}}
                  source={
                    isMuteUser
                      ? require('../../assets/common/mute-play.png')
                      : require('../../assets/common/mute.png')
                  }
                  onPress={this.props.muteRemoteUser}
                />
              ) : null}
              {/* 转让房主 */}
              {this.props.isManager ? (
                <ImageTitleButton
                  btnStyle={{
                    width: 50,
                    height: 50,
                    backgroundColor: '#C817EC',
                    borderRadius: 25,
                  }}
                  imageStyle={{width: 25, height: 25}}
                  title={'Transfer Owner'}
                  titleStyle={{color: Colors.fontBlackColor_31}}
                  source={require('../../assets/room/transfer.png')}
                  onPress={this.props.transferOwner}
                />
              ) : null}
              {/* 踢人 */}
              {this.props.isManager ? (
                <ImageTitleButton
                  btnStyle={{
                    width: 50,
                    height: 50,
                    backgroundColor: '#C817EC',
                    borderRadius: 25,
                  }}
                  imageStyle={{width: 25, height: 25}}
                  title={'Kick'}
                  titleStyle={{color: Colors.fontBlackColor_31}}
                  source={require('../../assets/room/kick.png')}
                  onPress={this.props.offUser}
                />
              ) : null}
            </View>
          </View>
          {/* <TextButton
            buttonStyle={{backgroundColor: '#FFCB26', marginTop: 50}}
            textStyle={{color: 'white'}}
            text={I18n.t('room.send_gift')}
            onPress={onSendGift} 
          /> */}
        </View>
        {/* </Modal> */}
      </View>
    );
  }
}

class GiftDialog extends Component {
  static propTypes = {
    visible: PropTypes.bool.isRequired,
    user: PropTypes.object.isRequired,
    onClose: PropTypes.func.isRequired,
    sendGift: PropTypes.func.isRequired,
    gifts: PropTypes.array.isRequired,
  };

  constructor(props) {
    super(props);

    this.state = {
      gifts: [...props.gifts],
      password: '',
      value: '',
    };
  }

  _selCoind = (coin) => {
    let newGift = this.state.gifts.map((item) => {
      return {
        ...item,
        selected: item.symbol == coin.symbol,
      };
    });

    this.setState({
      gifts: newGift,
    });
  };

  _renderGift = (item) => {
    const gift = item.item;
    console.log(gift);
    return (
      <View>
        <TouchableOpacity
          style={{
            marginRight: 10,
          }}
          onPress={() => {
            this._selCoind(gift);
          }}>
          <LinearGradient
            start={{x: 0, y: 1}}
            end={{x: 1, y: 1}}
            colors={gift.selected ? ['#CE18EC', '#6601F5'] : ['white', 'white']}
            style={{padding: 2, borderRadius: 10}}>
            <View
              style={{
                backgroundColor: 'white',
                justifyContent: 'center',
                alignItems: 'center',
                borderRadius: 8,
                padding: 20,
              }}>
              <CachedImage
                style={{width: 50, height: 50, borderRadius: 30}}
                source={{uri: gift.icon}}
              />
              <Text
                style={{
                  marginTop: 8,
                  fontWeight: 'bold',
                  color: '#6D03F4',
                  fontSize: 16,
                }}>
                {gift.symbol}
              </Text>
              <Text style={{color: '#6D03F4', fontSize: 12}}>
                {gift.balance}
              </Text>
            </View>
          </LinearGradient>
        </TouchableOpacity>
      </View>
    );
  };

  render() {
    const {user, visible, onClose} = this.props;
    return (
      <View
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          bottom: 0,
          width: visible ? '100%' : 0,
          height: '100%',
          backgroundColor: 'rgba(0,0,0,0.3)',
        }}>
        {/* <Modal
          onStartShouldSetResponder={() => false}
          animationType="slide"
          transparent
          visible={visible}
          onRequestClose={() => {}}
          onShow={() => {}}
        > */}
        <TouchableOpacity
          onPress={onClose}
          style={{flex: 1}}></TouchableOpacity>

        <KeyboardAvoidingView
          behavior={Platform.OS == 'ios' ? 'padding' : 'height'}
          style={{
            width: '100%',
            borderTopLeftRadius: 20,
            borderTopRightRadius: 20,
            backgroundColor: 'rgba(255,255,255,0.95)',
            paddingLeft: 20,
            paddingRight: 20,
            // marginBottom: -80,
          }}>
          <View style={{height: 110, flexDirection: 'row', marginTop: -40}}>
            <View
              style={{
                height: '100%',
                backgroundColor: 'white',
                borderRadius: 20,
                paddingLeft: 20,
                paddingRight: 20,
                flexDirection: 'column',
                justifyContent: 'center',
                alignItems: 'center',
                alignContent: 'center',
              }}>
              <Image
                style={{
                  width: 40,
                  height: 40,
                  marginBottom: 4,
                  alignSelf: 'center',
                }}
                source={require('../../assets/auction/auction.png')}
              />
              <Text
                style={{color: '#6D03F4', fontWeight: 'bold', fontSize: 16}}>
                {I18n.t('room.reward')}
              </Text>
              <Text style={{color: '#6D03F4', fontSize: 10}}>
                {I18n.t('room.send_gift')}
              </Text>
            </View>
            <View
              style={{
                backgroundColor: '#fff',
                borderRadius: 20,
                paddingLeft: 10,
                paddingRight: 10,
                flex: 1,
                flexDirection: 'row',
                justifyContent: 'center',
                alignItems: 'center',
                alignContent: 'center',
              }}>
              <Image
                style={{width: 60, height: 60, borderRadius: 80}}
                source={{uri: user.avatar}}
              />
              <View style={{marginLeft: 20}}>
                <Text
                  style={{color: '#6D03F4', fontWeight: 'bold', fontSize: 18}}
                  numberOfLines={1}>
                  {user.name}
                </Text>
                <Text
                  style={{color: '#6D03F4', fontSize: 12, marginTop: 2}}
                  numberOfLines={1}>
                  @{user.id}
                </Text>
              </View>
            </View>
          </View>

          <FlatList
            style={{marginTop: 20}}
            data={this.state.gifts}
            horizontal={true}
            showsHorizontalScrollIndicator={false}
            keyExtractor={(item, index) => index.toString()} // 给定的item生成一个不重复的key
            renderItem={this._renderGift}
          />
          <TextInput
            style={{
              height: 44,
              backgroundColor: '#fff',
              borderRadius: 30,
              paddingLeft: 22,
              marginTop: 20,
            }}
            keyboardType={'numeric'}
            placeholder={I18n.t('room.value')}
            placeholderTextColor="#a1a1a1"
            onChangeText={(text) => {
              this.setState({value: text});
            }}
          />
          <TextInput
            style={{
              height: 44,
              backgroundColor: '#fff',
              borderRadius: 30,
              marginTop: 20,
              paddingLeft: 22,
            }}
            secureTextEntry={true}
            placeholder={I18n.t('room.password')}
            placeholderTextColor="#a1a1a1"
            onChangeText={(text) => {
              this.setState({password: text});
            }}
          />
          <LinearButton
            buttonStyle={{
              backgroundColor: '#FFCB26',
              marginTop: 20,
              marginBottom: 40,
            }}
            textStyle={{color: 'white'}}
            text={I18n.t('room.done')}
            onPress={() => {
              let selCoins = this.state.gifts.filter((item) => item.selected);
              this.props.sendGift(
                selCoins,
                this.state.password,
                this.state.value,
              );
            }}></LinearButton>
        </KeyboardAvoidingView>
        {/* </Modal> */}
      </View>
    );
  }
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  currentRoom: state.User.currentRoom,
  speakers: state.User.speakers,
  listeners: state.User.listeners,
  offlineUser: state.User.offlineUser,
  coins: state.Chain.coins.map((item) => {
    return {
      ...item,
      selected: false,
    };
  }),
  roomKey: state.Layout.roomKey,
  gasSymbol: state.Chain.gasSymbol,
  swapSymbol: state.Chain.swapSymbol,
  muteUsers: state.User.muteUsers,
  speakingUsers: state.User.speakingUsers,
  widgetLayout: state.Layout.widgetLayout,
});
const mapDispatchToProps = (dispatch) => ({
  setCurrentRoomListener: (item) => dispatch(setCurrentRoomListener(item)),
  setCurrentRoomSpeaker: (item) => dispatch(setCurrentRoomSpeaker(item)),
  setRoomWidgetLayout: (item) => dispatch(setRoomWidgetLayout(item)),
  updateUserInfo: (item) => dispatch(updateUserInfo(item)),
  setRoomKey: (item) => dispatch(setRoomKey(item)),
  queryWalltBalance: () => dispatch(queryWalltBalance()),
  setCurrentRoom: (item) => dispatch(setCurrentRoom(item)),
});

export default connect(mapStateToProps, mapDispatchToProps)(RoomScreen);
